AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )

include('shared.lua')

function ENT:SpawnFunction( ply, tr )

	if ( !tr.Hit ) then return end
	
	local SpawnPos = tr.HitPos
	local ent = ents.Create( "lud_life_tree" )
	ent:SetPos( SpawnPos )
	ent:Spawn()
	ent:DropToFloor()
	ent:Activate()
//	ent.SPL = ply
	return ent
end

local function physgunPickup( userid, Ent )  	
	if Ent:GetClass() == "lud_life_tree" then  		
		if not userid:IsAdmin() then
			return false
		end
	end  
end     
hook.Add( "PhysgunPickup", "Nope", physgunPickup )

function ENT:CanTool()
	return false
end

function ENT:GravGunPunt()
	return false
end

function ENT:GravGunPickupAllowed()
	return false
end

function ENT:Initialize()
	self.Entity:SetModel( "models/props_foliage/tree_deciduous_01a.mdl" )
//	self.Entity:PhysicsInit( SOLID_NONE )
//	self.Entity:SetMoveType( MOVETYPE_NONE )
//	self.Entity:SetSolid( SOLID_NONE )
//	self.Entity:DrawShadow( false )
		local P = 0
		local Y = math.random(0,180)
		local R = 0
		self.Roots = self:GetPos()
		self.Turn=Angle(P,Y,R)
	self:SetAngles(Angle(P,Y,R))
	ent:DropToFloor()
//	local phys = self.Entity:GetPhysicsObject()
//	if (phys:IsValid()) then
//		phys:Wake()
//		phys:EnableMotion(false)
//		phys:EnableCollisions(true)
//	end
	self.BaseClass.Initialize(self)
	RD_Register(self, true)--For Environments Compatibility
	self:Grassonly()
end

function ENT:Grassonly()
	local trace = {}
 
	trace.start = self:GetPos()
	trace.endpos = self:GetPos()-Vector(0,0,100)
	trace.filter = self
	local Land = util.TraceLine( trace )
	if Land.MatType ~= 68 and Land.HitTexture~="**displacement**" then
		self:Remove()
	end
//	PrintTable(Land)
	return 
end

function ENT:NoSpace()
	local pos = self:GetPos()
	if (!Environments.FindEnvironmentOnPos(pos)) or (self:WaterLevel() > 0) then
		self:Remove()
	//	Msg("LifeTrees: Was in a bad place")
	end
end

function ENT:JustRight()
	if IsEntity(self.Environment) then
		if self.environment:GetTemperature(self) > 300 then
			self:Remove()
//			Msg("LifeTrees: TOO HOT!!!! D:")
		end
	end
end

function ENT:OnRemove()
	self.BaseClass.OnRemove(self)
end

function ENT:Proc_Air()
	if IsEntity(self.environment) then
		if self.environment:GetO2Percentage() < 25 and self.environment:GetPressure() < 1.5 then
			self.environment:Convert(-1, 0, 500)
		end
	end
end


function ENT:Level()
	self:SetPos(self.Roots)
	self:SetAngles(self.Turn)
	self:GetPhysicsObject():Sleep()--TEST!
end

function ENT:Think()
	self.BaseClass.Think(self)
	self:NoSpace()
	self:JustRight()
	self:Proc_Air()
	self:Level()
	self.Entity:NextThink( CurTime() + 1 )
	return true
end